package com.example.ktapplication.activity

import android.content.Intent
import android.graphics.ColorMatrix
import android.graphics.ColorMatrixColorFilter
import android.graphics.Paint
import android.os.Bundle
import android.view.Gravity
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.viewpager2.widget.ViewPager2
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.ktapplication.AppGlobals
import com.example.ktapplication.R
import com.example.ktapplication.adapter.ViewPager2Adapter
import com.example.ktapplication.base.BaseActivity
import com.example.ktapplication.databinding.ActivityMainBinding
import com.example.ktapplication.fragment.HomeFragment
import com.example.ktapplication.fragment.NavFragment
import com.example.ktapplication.fragment.ProjectFragment
import com.example.ktapplication.fragment.SystemFragment
import com.example.ktapplication.fragment.VideoFragment
import com.example.ktapplication.model.LogoutViewModel
import com.example.ktapplication.net.RetrofitClient
import com.example.ktapplication.state.LogoutState
import com.example.ktapplication.utils.SpUtils
import com.example.ktapplication.utils.event.Event
import com.example.ktapplication.utils.event.EventBusUtil
import com.google.firebase.crashlytics.buildtools.reloc.com.google.common.eventbus.Subscribe
import com.tencent.bugly.crashreport.CrashReport
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MainActivity : BaseActivity<ActivityMainBinding>() {

    private var stateJob: Job? = null

    private val logout by lazy {
        ViewModelProvider(this)[LogoutViewModel::class.java]
    }

    private val fragmentList: MutableList<Fragment> by lazy {
        mutableListOf<Fragment>().apply {
            add(HomeFragment())
            add(VideoFragment())
            add(SystemFragment())
            add(ProjectFragment())
            add(NavFragment())
        }
    }

    override fun getViewBind(): ActivityMainBinding {
        return ActivityMainBinding.inflate(layoutInflater)
    }

    override fun isRegisterEvent(): Boolean {
        return true
    }

    override fun onDate(savedInstanceState: Bundle?) {

    }

    override fun onViewBing() {
        initView()
        registerFlow()
    }

    fun initView() {
        initMenuView()
        initViewPager()
    }




    private fun initMenuView() {
        if (!SpUtils.getInstance().getValue("LOGIN", false)) {
            binding.txtLoginTip.visibility = View.VISIBLE
            Glide.with(AppGlobals.getApplication())
                .load(R.mipmap.icon_mine)
                .apply(RequestOptions.circleCropTransform())
                .into(binding.imgHeader)
            binding.btnLogout.visibility = View.INVISIBLE
        } else {
            binding.txtLoginTip.visibility = View.INVISIBLE
            binding.btnLogout.visibility = View.VISIBLE
            Glide.with(AppGlobals.getApplication())
                .load(R.mipmap.icon_header)
                .apply(RequestOptions.circleCropTransform())
                .into(binding.imgHeader)
        }
        binding.imgHeader.setOnClickListener {
            if (!SpUtils.getInstance().getValue("LOGIN", false)) {
                val intent = Intent(this, LoginActivity::class.java)
                startActivity(intent)
            }
        }
        binding.btnLogout.setOnClickListener {
            if (SpUtils.getInstance().getValue("LOGIN", true)) {
                showDialog("账号登录中...", "login")
                logout.logout()
            }
        }
        binding.llSetting.setOnClickListener(View.OnClickListener {
           SettingActivity.start(this)
        })
        binding.llCollect.setOnClickListener{
            if ( SpUtils.getInstance().getValue("LOGIN", false)){
                CollectActivity.start(this)
            }else{
                LoginActivity.start(this@MainActivity)
            }
        }
        binding.llAbout.setOnClickListener{
           AboutActivity.start(this@MainActivity)
        }
    }

    private fun initViewPager() {
        binding.viewPager2.apply {
            offscreenPageLimit = fragmentList.count()
            //禁止滑动
            isUserInputEnabled = false
            adapter = ViewPager2Adapter(this@MainActivity, fragmentList)
            //当viewpage2页面切换时nav导航图标也跟着切换
            registerOnPageChangeCallback(object :
                ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    super.onPageSelected(position)
                    binding.bottomNavigationView.menu.getItem(position).isChecked = true
                    execFragmentState(position)
                }
            })
        }
        //当nav导航点击切换时，viewpager2也跟着切换页面
        binding.bottomNavigationView.setOnItemSelectedListener { item ->
            var currIndex = 0
            when (item.itemId) {
                R.id.navigation_home -> {
                }

                R.id.navigation_video -> {
                    currIndex = 1
                }

                R.id.navigation_system -> {
                    currIndex = 2
                }

                R.id.navigation_project -> {
                    currIndex = 3
                }

                R.id.navigation_mine -> {
                    currIndex = 4
                }
            }
            binding.viewPager2.currentItem = currIndex
            true
        }
    }

    private fun execFragmentState(position: Int) {
        EventBusUtil.eventBus.post(Event.MainTab(position))
    }

    private fun registerFlow() {
        stateJob = lifecycleScope.launch(Dispatchers.IO) {
            ///IO线程
            logout.state.collect { state ->
                dismissDialog()
                when (state) {
                    is LogoutState.OnSuccess -> {
                        if (state.logout != null) {
                            if (state.logout!!.errorCode == 0) {
                                withContext(Dispatchers.Main) {
                                    ///退出登录
                                    RetrofitClient.clearCookie()
                                    SpUtils.getInstance().setValue("LOGIN", false)
                                    binding.txtLoginTip.visibility = View.VISIBLE
                                    Glide.with(AppGlobals.getApplication())
                                        .load(R.mipmap.icon_mine)
                                        .apply(RequestOptions.circleCropTransform())
                                        .into(binding.imgHeader)
                                    binding.btnLogout.visibility = View.INVISIBLE
                                    binding.drawerLayout.close()
                                }
                            } else {
                                showToast(state.logout!!.errorMsg)
                            }
                            state.logout!!.count += 1
                        }
                    }

                    is LogoutState.OnError -> {
                        val error = state.exception!!.message.toString()
                        showToast(error)
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        stateJob!!.cancel()
        super.onDestroy()
    }

    @Subscribe
    fun onMainClickFind(event: Event.MainClickFind) { //搜索按钮事件
        ///跳转查找Activity
        val intent = Intent(this, HostSearchActivity::class.java)
        startActivity(intent)
    }

    @Subscribe
    fun onMainClickMenu(event: Event.MainClickMenu) { //菜单按钮事件
        binding.drawerLayout.openDrawer(Gravity.LEFT);
    }

    @Subscribe
    fun onLoginSuc(event: Event.LoginSuc) { //登录成功事件
        ///登录成功刷新界面，保存登录标记
        lifecycleScope.launch(Dispatchers.Main) {
            SpUtils.getInstance().setValue("LOGIN", true)
            binding.txtLoginTip.visibility = View.INVISIBLE
            binding.btnLogout.visibility = View.VISIBLE
            Glide.with(this@MainActivity)
                .load(R.mipmap.icon_header)
                .apply(RequestOptions.circleCropTransform())
                .into(binding.imgHeader)
        }
    }

    @Subscribe
    fun OnNeedLogin(event: Event.NeedLogin) { //登录成功事件
        LoginActivity.start(this@MainActivity)
    }
}